#include <bits/stdc++.h>

using namespace std;
using ll = long long;
const int maxn = 1e5 + 10;
vector<int> primes;
vector<bool> isprime(maxn, true);

void init() {
    // fill(isprime.begin(), isprime.end(), true);
    isprime[0] = isprime[1] = false;
    for (int i = 2; i * i <= maxn; i++) {
        if (isprime[i]) {
            for (int j = i * i; j <= maxn; j += i)isprime[j] = false;
        }
    }
    for (int i = 2; i < maxn; i++) {
        if (isprime[i])primes.push_back(i);
    }
}

ll k(ll n, ll p) {
    ll s = 0;
    for (ll i = p; i <= n; i += p) {
        ll t = 0;
        for (ll j = p; j <= i; j *= p) {
            if (i % j != 0)break;
            t++;
        }
        s += i * t;
    }
    return s;
}

ll f(ll n, ll r, ll p) {
    return k(n, p) - k(r, p) - k(n - r, p);
}

ll pw(ll a, ll b, ll m) {
    a %= m;
    long long res = 1;
    while (b > 0) {
        if (b & 1) res = res * a % m;
        a = a * a % m;
        b >>= 1;
    }
    return res;
}

int main() {
    init();
    // copy(primes.begin(),primes.end(),ostream_iterator<int>(cout," "));
    //cout << primes.size() << endl;
    int T;
    cin >> T;
    while (T--) {
        ll n, m, q, r;
        cin >> n >> m >> q;
        while (q--) {
            cin >> r;
            ll ans = 1;
            for (auto p: primes) {
                if (p > n)break;
                ans = ans * pw(p, f(n, r, p), m) % m;
            }
            cout << ans << endl;
        }
    }
}